﻿#include "srcwidget.h"
#include "ui_srcwidget.h"
#include <QDebug>

SrcWidget::SrcWidget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::SrcWidget)
{
    ui->setupUi(this);

    connect(ui->toolButton, &QToolButton::clicked, this, &SrcWidget::toolButtonClicked);
    connect(ui->pushButton_add, &QPushButton::clicked, this, &SrcWidget::pushButtonAddClicked);
    connect(ui->pushButton_del, &QPushButton::clicked, this, &SrcWidget::pushButtonDelClicked);

    m_viewWidget = new QWidget;
    ui->scrollArea->setWidget(m_viewWidget);
    ui->scrollArea->setWidgetResizable(true); // 设置为自动调整大小

    ColumnMapping* cm = new ColumnMapping;
    cm->setSeq(QString::number(m_LatestSeq) + ".");
    ++m_LatestSeq;
    connect(cm, &ColumnMapping::updateColumnSignal, this, &SrcWidget::updateColumnMap);

    QVBoxLayout* layout = new QVBoxLayout;
    layout->addWidget(cm);
    m_viewWidget->setLayout(layout);

}

SrcWidget::~SrcWidget()
{
    delete ui;
}

QVector<COLUMN_MAP> SrcWidget::getDataMapVector()
{
    return dataVector;
}

QString SrcWidget::getFilePath()
{
    return ui->lineEdit->text();
}


void SrcWidget::toolButtonClicked()
{
    QFileDialog dl;

    QString filePath = "";

    filePath = dl.getOpenFileName(nullptr, u8"选择输入文件", QApplication::applicationDirPath(), u8"excel文件 (*.xls *.xlsx)");

    ui->lineEdit->setText(filePath);
}


void SrcWidget::pushButtonAddClicked()
{
    ColumnMapping* cm = new ColumnMapping;
    cm->setSeq(QString::number(m_LatestSeq) + ".");
    ++m_LatestSeq;
    connect(cm, &ColumnMapping::updateColumnSignal, this, &SrcWidget::updateColumnMap);
    m_viewWidget->layout()->addWidget(cm);

    // 等待一段时间，确保布局更新
    QTimer::singleShot(100, this, [&]() {
        ui->scrollArea->verticalScrollBar()->setValue(ui->scrollArea->verticalScrollBar()->maximum());
    });
}

void SrcWidget::pushButtonDelClicked()
{
    QList<ColumnMapping*> allCM = m_viewWidget->findChildren<ColumnMapping *>(QString(), Qt::FindDirectChildrenOnly);

    if (allCM.isEmpty()) return;

    ColumnMapping* lastCm = allCM.last();
    delete lastCm;
    allCM.removeLast();

    --m_LatestSeq;

    // 等待一段时间，确保布局更新
    QTimer::singleShot(100, this, [&]() {
        ui->scrollArea->verticalScrollBar()->setValue(ui->scrollArea->verticalScrollBar()->maximum());
    });
}


void SrcWidget::updateColumnMap()
{
    QList<ColumnMapping*> allCM = m_viewWidget->findChildren<ColumnMapping *>(QString(), Qt::FindDirectChildrenOnly);
    dataVector.clear();
    for(auto const& cm : std::as_const(allCM)) {
        COLUMN_MAP cmStruct;
        cm->getColumnMap(&cmStruct);

        // 更新核心查找数据
        dataVector.append(cmStruct);

    }
}
